﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    /// <summary>
    /// ObjectExtension
    /// </summary>
    public static partial class ObjectExtension
    {
        /// <summary>
        /// 数据类型转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <returns></returns>
        public static T As<T>(this object @this)
        {
            return (T) @this;
        }
        /// <summary>
        /// 数据类型转换,转换失败返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <returns></returns>
        public static T AsOrDefault<T>(this object @this)
        {
            try
            {
                return (T) @this;
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        /// <summary>
        /// 确定当前的 System.Type 的实例是否可以从指定 &lt;T&gt; 的实例分配。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <returns></returns>
        public static bool IsAssignableFrom<T>(this object @this)
        {
            var type = @this.GetType();
            return type.IsAssignableFrom(typeof (T));
        }
        /// <summary>
        ///  确定当前的 System.Type 的实例是否可以从指定 Type 的实例分配
        /// </summary>
        /// <param name="this"></param>
        /// <param name="targetType"></param>
        /// <returns></returns>
        public static bool IsAssignableFrom(this object @this, Type targetType)
        {
            var type = @this.GetType();
            return type.IsAssignableFrom(targetType);
        }
    }
}